using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    [SerializeField] private float swordAttackCD = 0.5f;
    
    public bool attackButtonDown = false;


    void Update()
    {
        PlayerInputs();
        Attack();  
    }

    private void PlayerInputs()
    {
        if (Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.RightControl))
        {
            if (PlayerController.GetInstance().isAttacking)
            {
                StartCoroutine(GameSceneManager.GetInstance().ShowTipsRountine("攻击冷却中！", swordAttackCD));
                return;
            }
            StartAttacking();
        }
        if (Input.GetMouseButtonUp(0) || Input.GetKeyUp(KeyCode.LeftControl) || Input.GetKeyUp(KeyCode.RightControl))
        {
            StopAttacking();
        }
    }

    private void StartAttacking()
    {
        attackButtonDown = true;
    }

    private void StopAttacking()
    {
        attackButtonDown = false;
    }

    private void Attack()
    {
        bool isAttacking = PlayerController.GetInstance().isAttacking;
        if (attackButtonDown && !isAttacking && !IsPointerOverUI())
        {
            PlayerController.GetInstance().isAttacking = true;
            StartCoroutine(AttackCDRoutine());
        }
        
    }

    private IEnumerator AttackCDRoutine()
    {
        PlayerController.GetInstance().Attack();
        yield return new WaitForSeconds(swordAttackCD);
        PlayerController.GetInstance().isAttacking = false;
    }

    bool IsPointerOverUI()
    {
        if (EventSystem.current == null)
        {
            return false;
        }

        return EventSystem.current.IsPointerOverGameObject();
    }

}
